<template>
  <div>
    <el-form :inline="true" :model="form" class="custom-left-form">
      <el-form-item class="custom-label-item">
        <el-select v-model="queryParams.ID_ORG" placeholder="请选择机构" style="width: 200px">
          <el-option v-for="item in provinceOptions" :key="item.ID_ORG" :label="item.NA" :value="item.ID_ORG"/>
        </el-select>
      </el-form-item>

      <!--  日期组件   -->
      <el-form-item label="日期">
        <el-date-picker
            v-model="queryParams.date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="changeDate">
        </el-date-picker>
      </el-form-item>

      <!-- 新增的字典数据下拉框 -->
      <el-form-item class="custom-label-item">
        <el-select
            v-model="selecteBusinessInputType"
            placeholder="请选操作业务"
            style="width: 220px"
            @change="handleDictChange"
        >
          <el-option
              v-for="item in businessList"
              :key="item.dicType"
              :label="item.dicName"
              :value="item.dicType"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="success" @click="queryDicData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="exportData()">导出</el-button>
      </el-form-item>
    </el-form>
    <div class="check-dic-list">
      <div class="table-container">
        <el-table :data="tableData" style="width: 100%" :fit="true">
          <el-table-column fixed prop="code" label="上传编码"></el-table-column>
          <el-table-column prop="name" label="上传名称"></el-table-column>

          <!--          <el-table-column fixed
                                     :prop="selecteBusinessInput?.dicType === '1' ? 'jyxx' : (selecteBusinessInput?.dicType === '2' ? 'jcxx' : 'ID_PI')"
                                     label="名称"
                    ></el-table-column>
                    <el-table-column fixed
                                     :prop="selecteBusinessInput?.dicType === '1' ? 'jyxx' : (selecteBusinessInput?.dicType === '2' ? 'jcxx' : 'ID_PI')"
                                     label="编码"
                    ></el-table-column>-->
        </el-table>
      </div>
      <!-- 分页插件 -->
      <div class="PaginationPlugin">
        <el-pagination
            v-if="pageObj"
            background
            layout="sizes, total, prev, pager, next, jumper"
            :page-size="pageObj.maxCount"
            :total="pageObj.totalCount"
            :current-page.sync="pageObj.currentPage"
            @size-change="pageObj.sizeChange"
            @current-change="pageObj.pageChange"
        />
      </div>
    </div>
  </div>
</template>

<script>

import moment from 'moment'
import {queryDicList} from "@/views/ThirdLevelPubHosPerforAss/dicUplod/dicUplod"


export default {
  mounted() {
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth(); // 月份从0开始（0-11）
    // 当月第一天
    const firstDay = new Date(currentYear, currentMonth, 1);
    // 当月最后一天（下个月第一天的前一天）
    const lastDay = new Date(currentYear, currentMonth + 1, 0);
    // 设置默认日期范围
    this.queryParams.date = [firstDay, lastDay];
  },
  data() {
    return {
      //业务下拉框
      businessList: [
        {dicName: 'TCMMS51087_剂型字典', dicType: '1', viewName: 'interface.V_PCZYY_SJGLYYJXKH_JX'},
        {dicName: 'TCMMS51087_中医类操作字典', dicType: '2', viewName: 'interface.V_PCZYY_SJGLYYJXKH_ZYCZ'},
        {dicName: 'TCMMS51087_给药途径字典', dicType: '3', viewName: 'interface.V_PCZYY_SJGLYYJXKH_GYTJ'}
      ],
      selecteBusinessInput: null,  // 用于存储选中的字典项对象
      selecteBusinessInputType: null,
      commonparams: {
        page: 1,
        size: 10
      },
      pageObj: {
        maxCount: 10,
        totalCount: 0,
        currentPage: 1,
        sizeChange: (page) => {
          this.handleSizeChange(page)
        },
        pageChange: (page) => {
          this.paginationPluginpageChange(page)
        }
      },
      pickerOptions: {
        // 禁用日期规则
        disabledDate(time) {
          return time.getTime() > Date.now() - 86400000
        }
      },
      queryParams: {ID_ORG: '68401005caaa060001b96f9f', date: []},
      provinceOptions: [{ID_ORG: '68401005caaa060001b96f9f', NA: '平昌县中医医院'}],
      form: {},
      tableData: []
    }
  },
  methods: {
    async exportData() {
      debugger
      if (!this.selecteBusinessInput) {
        this.$message.error('请选择操作业务')
        return false
      }
      console.log('选中的业务名称:', this.selecteBusinessInput.dicName);
      console.log('选中的业务类型:', this.selecteBusinessInput.dicType);
      console.log('选中的业务视图:', this.selecteBusinessInput.viewName);
      //导出<el-table> 中所有页的数据 生成csv 文件并保存在桌面上 csvFile文件夹中,如果没有该文件夹就新建
      try {
        // 1. 显示加载中提示
        this.$message({
          type: 'loading',
          message: '正在导出数据，请稍候...',
          duration: 0, // 持续显示
          forbidClick: true,
          showClose: true // 可选：显示关闭按钮
        });

        // 2. 获取所有页的数据
        const allData = await this.getAllTableData();

        if (allData.length === 0) {
          this.$message.warning('没有数据可导出');
          return false;
        }

        // 3. 转换数据为CSV格式
        // 根据业务类型转换数据为CSV
        let csvContent = ''
        switch(this.selecteBusinessInput.dicType) {
          case '1':
            csvContent = this.convertToCsvJX(allData)
            break
          case '2':
            csvContent = this.convertToCsvZYCZ(allData)
            break
          case '3':
            csvContent = this.convertToCsvGYTJ(allData)
            break
          default:
            throw new Error('未知的业务类型')
        }
        // 4. 生成并下载CSV文件
        this.downloadCsv(csvContent, this.selecteBusinessInput.dicName);

        // 5. 提示导出成功
        this.$message.success('数据导出成功，请保存到桌面的csvFile文件夹');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请重试');
      } finally {
        // 关闭加载提示
        this.$message.closeAll();
      }
    },
    // 获取所有页的数据
    async getAllTableData() {
      const originalPageNum = this.commonparams.page;
      const originalPageSize = this.commonparams.size;
      const allData = [];

      try {
        // 先获取第一页数据，确定总页数
        this.commonparams.page = 1;
        this.commonparams.size = 1000; // 每次获取1000条，可根据实际情况调整

        const firstPageData = await this.fetchPageData();
        allData.push(...firstPageData.data);

        // 计算总页数
        const totalPages = Math.ceil(firstPageData.total / this.commonparams.size);

        // 逐页获取剩余数据
        for (let page = 2; page <= totalPages; page++) {
          this.commonparams.page = page;
          const pageData = await this.fetchPageData();
          allData.push(...pageData.data);
        }

        return allData;
      } finally {
        // 恢复原始分页参数
        this.commonparams.page = originalPageNum;
        this.commonparams.size = originalPageSize;
      }
    },
    // 获取单页数据
    async fetchPageData() {
      const start = this.queryParams.date ? moment(this.queryParams.date[0]).format('YYYY-MM-DD') : '';
      const end = this.queryParams.date ? moment(this.queryParams.date[1]).format('YYYY-MM-DD') : '';

      const params = {
        pageSize: this.commonparams.size,
        pageNum: this.commonparams.page,
        beginTime: start,
        endTime: end,
        dicName: this.queryParams.dicName,
        dicType: this.queryParams.dicType,
        idOrg: this.queryParams.ID_ORG,
        viewName: this.queryParams.viewName
      };

      return await queryDicList(params);
    },
    /**
     * 剂型数据CSV转换
     */
    convertToCsvJX(data) {
      const headers = ['jixingdm', 'jixingmc']
      const fields = ['code', 'name']
      return this.baseConvertToCsv(data, headers, fields)
    },

    /**
     * 中医操作CSV转换
     */
    convertToCsvZYCZ(data) {
      const headers = ['zylczdm', 'zylczmc']
      const fields = ['code', 'name']
      return this.baseConvertToCsv(data, headers, fields)
    },

    /**
     * 给药途径CSV转换
     */
    convertToCsvGYTJ(data) {
      const headers = ['gytjdm', 'gytjmc']
      const fields = ['code', 'name']
      return this.baseConvertToCsv(data, headers, fields)
    },

    /**
     * CSV转换基础方法
     */
    baseConvertToCsv(data, headers, fields) {
      if (!data || data.length === 0) return ''

      // 处理表头
      const processedHeaders = headers.map(header =>
          `"${header.toString().replace(/"/g, '""')}"`
      )

      // 构建CSV内容
      let csv = processedHeaders.join(',') + '\n'

      debugger
      // 添加数据行
      data.forEach(row => {
        const values = fields.map(field => {
          const value = row[field] || ''
          // 处理特殊字符
          return `"${value.toString()
              .replace(/"/g, '""')
              .replace(/\n/g, ' ')
              .replace(/\r/g, '')}"`
        })
        csv += values.join(',') + '\n'
      })

      return csv
    },

// 下载CSV文件
    downloadCsv(content, fileName) {
      // 创建Blob对象
      const blob = new Blob(['\ufeff' + content], {type: 'text/csv;charset=utf-8;'});

      // 创建下载链接
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;

      // 生成文件名（包含时间戳防止重复）
      // const timestamp = new Date().getTime(); a.download = `${fileName}_${timestamp}.csv`;
      a.download = `${fileName}.csv`;

      // 模拟点击下载
      document.body.appendChild(a);
      a.click();

      // 清理
      setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }, 100);
    },
    // 处理字典选择变化
    handleDictChange(selectedItemType) {debugger
      if (selectedItemType) {
        // 根据选中的 dicType，从 businessList 中匹配对应的完整 item
        const selectedItem = this.businessList.find(item => item.dicType === selectedItemType);

        // 获取选中项的dicName和dicType
        console.log('选中的业务名称:', selectedItem.dicName);
        console.log('选中的业务类型:', selectedItem.dicType);
        console.log('选中的业务视图:', selectedItem.viewName);

        this.selecteBusinessInput=selectedItem;
        // 也可以将值存储到查询参数中，方便后续查询使用
        this.queryParams.dicName = selectedItem.dicName;
        this.queryParams.dicType = selectedItem.dicType;
        this.queryParams.viewName = selectedItem.viewName;
      } else {
        // 清除选中状态时的处理
        this.queryParams.dicName = '';
        this.queryParams.dicType = '';
        this.queryParams.viewName = '';
      }
    },
    //当日期变化时,处理事件
    changeDate() {
      this.queryDicData()
    },
    async queryDicData() {
      debugger

      if (!this.selecteBusinessInput) {
        this.$message.error('请选择操作业务')
        return false
      }

      const start = moment(this.queryParams.date[0]).format('YYYY-MM-DD')
      const end = moment(this.queryParams.date[1]).format('YYYY-MM-DD')
      let params = {
        pageSize: this.commonparams.size,
        pageNum: this.commonparams.page,
        beginTime: start,
        endTime: end,
        dicName: this.queryParams.dicName,
        dicType: this.queryParams.dicType,
        idOrg: this.queryParams.ID_ORG,
        viewName: this.queryParams.viewName
      }
      try {
        const res = await queryDicList(params)
        if (res.code===99){
          this.$message.error(res.msg)
          return false
        }
        console.log('返回:', res)
        this.tableData = res.data || []
        this.pageObj.totalCount = res.total || 0
      } catch (error) {
        console.error('查询中心账单信息失败:', error)
        this.ybzxList = []
        this.pageObj.totalCount = 0
      }
    },
    handleSizeChange(page) {
      this.commonparams.size = page
      this.commonparams.page = 1
      this.pageObj.maxCount = page
      this.pageObj.currentPage = 1
      this.queryDicData()
    },
    // 页码变化
    paginationPluginpageChange(val) {
      this.commonparams.page = val
      this.queryDicData()
    }
  }
}

</script>

<style scoped>

/* 核心左对齐样式 */
.custom-left-form {
  display: flex;
  flex-wrap: wrap;
  align-items: left;
}

::v-deep .custom-label-item {
  font-size: var(--label-font-size, 20px) !important;
  color: var(--label-color, red) !important; /* 默认颜色 */
  /* font-weight: var(--label-weight, normal);*/
}

::v-deep .ellipsis-text {
  display: inline-block;
  max-width: 80%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}


/* 基础表格样式 */
::v-deep .el-table {
  border: 1px solid #000 !important;
  border-color: #000 !important; /* 表格外边框 */
}

/* 单元格边框设置 */
::v-deep .el-table td,
::v-deep .el-table th {
  border: 1px solid #000 !important;
  border-color: #000 !important; /* 单元格边框 */
}

/* 表头专属样式 */
::v-deep .el-table th {
  font-weight: 900 !important; /* 数字加粗级别（比bold更粗） */
  color: #000 !important; /* 表头文字颜色 */
  background-color: #f5f7fa !important; /* 保留默认背景色 */
}


</style>